package com.boot.app.base.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.api.ApiResult;
import com.boot.app.base.domain.BaseApp;
import com.boot.app.base.service.IBaseAppService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("base/app")
public class BaseAppController {

    private final IBaseAppService service;

    @Autowired
    public BaseAppController(
        IBaseAppService appService
    ){
        this.service = appService;
    }

    @GetMapping("{id}")
    public ApiResult<BaseApp> getApp(@PathVariable("id") long id){
        BaseApp app = service.getById(id);
        return ApiResult.success(app);
    }

    @GetMapping("page/{page}/{size}")
    public ApiResult<Page<BaseApp>> getAppPage(@PathVariable("page")int page, @PathVariable("size")int size, BaseApp app){
        LambdaQueryWrapper<BaseApp> wrapper = new LambdaQueryWrapper<>();
        if(NumberUtil.isValidNumber(app.getId())) wrapper.like(BaseApp::getId, app.getId());
        if(StrUtil.isNotBlank(app.getCode())) wrapper.like(BaseApp::getCode, app.getCode());
        if(StrUtil.isNotBlank(app.getName())) wrapper.like(BaseApp::getName, app.getName());
        wrapper.orderByAsc(BaseApp::getOrdIdx);
        Page<BaseApp> appPage = service.page(new Page<>(page,size), wrapper);
        return ApiResult.success(appPage);
    }

    @GetMapping("list")
    public ApiResult<List<BaseApp>> getAppList(){
        LambdaQueryWrapper<BaseApp> wrapper = new LambdaQueryWrapper<>();
        List<BaseApp> list = service.list(wrapper);
        return ApiResult.success(list);
    }

    @PostMapping()
    public ApiResult<?> postOrPutApp(@RequestBody BaseApp app){
        service.saveOrUpdate(app);
        return ApiResult.success();
    }

    @DeleteMapping("{id}")
    public ApiResult<?> deleteApp(@PathVariable("id") long id){
        service.removeById(id);
        return ApiResult.success();
    }

}
